package com.example.dubbo.order.core.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;

@Slf4j
public class Converter {

    public static <T> T convert(Object o, Class<T> tClass) {
        if (o == null) {
            return null;
        }
        try {
            T t = tClass.newInstance();
            BeanUtils.copyProperties(o, t);
            return t;
        } catch (Exception e) {
            String errorMsg = String.format("ObjectConverter convert Exception, o=%s, tClass=%s, %s", JSON.toJSONString(o), tClass.getName(), e.getMessage());
            log.error(errorMsg, e);
        }
        return null;
    }

    public static <T> T convert(Object o, Class<T> tClass, String... ignoreProperties) {
        if (o == null) {
            return null;
        }
        try {
            T t = tClass.newInstance();
            BeanUtils.copyProperties(o, t, ignoreProperties);
            return t;
        } catch (Exception e) {
            String errorMsg = String.format("ObjectConverter convert Exception, o=%s, tClass=%s, ignoreProperties=%s， %s", JSON.toJSONString(o), tClass.getName(), JSON.toJSONString(ignoreProperties), e.getMessage());
            log.error(errorMsg, e);
        }
        return null;
    }


    public static <T> List<T> convertList(List list, Class<T> tClass) {
        if (list == null) {
            return null;
        }
        List<T> resultList = Lists.newArrayList();
        try {
            for (Object t : list) {
                resultList.add(convert(t, tClass));
            }

        } catch (Exception e) {
            String errorMsg = String.format("ObjectConverter convertList Exception, o=%s, tClass=%s， %s",
                    JSON.toJSONString(list), tClass.getName(), e.getMessage());
            log.error(errorMsg, e);
        }
        return resultList;
    }

    public static <T> List<T> convertList(List list, Class<T> tClass, String... ignoreProperties) {
        List<T> resultList = Lists.newArrayList();
        if (list == null) {
            return resultList;
        }
        try {
            for (Object o : list) {
                resultList.add(convert(o, tClass, ignoreProperties));
            }

        } catch (Exception e) {
            String errorMsg = String.format("ObjectConverter convertList Exception, o=%s, tClass=%s, ignoreProperties=%s， %s",
                    JSON.toJSONString(list), tClass.getName(), JSON.toJSONString(ignoreProperties), e.getMessage());
            log.error(errorMsg, e);
        }
        return resultList;
    }
}
